using UnityEngine;
using System.Collections;

public class AutomaticTranslation : MonoBehaviour
{
    #region Attributes

    public bool pingPong = false;
    public Vector3 movingAxis = Vector3.zero;
    public float speed = 1.0f;
    public float distance = 3.0f;
    public bool resetScript = false;

    private bool movementComplete = false;
    private Vector3 startPosition;
    private Vector3 endPosition;
    private float displacement = 0;

    #endregion

    #region Methods

    private void calculatePositions()
    {
        this.startPosition = this.transform.position;
        this.endPosition = this.startPosition + this.movingAxis * this.distance;
    }

    #endregion

    #region Unity Methods

    // Use this for initialization
    void Start()
    {
        calculatePositions();
    }

    // Update is called once per frame
    void FixedUpdate()
    {
        if (!movementComplete)
        {
            // displacement esta en el intervalo [0,1]
            // 0 => Lerp retorna startPosition
            // 1 => Lerp retorna endPosition
            this.displacement += this.speed * Time.deltaTime;            
            this.transform.position = Vector3.Lerp(this.startPosition, this.endPosition, this.displacement / this.distance);

            if (this.transform.position == this.endPosition)
            {
                this.displacement = 0;
                if (!this.pingPong)
                {
                    this.movementComplete = true;
                }
                else
                {
                    this.movingAxis *= -1;
                    calculatePositions();
                }
            }
        }

        if (this.resetScript)
        {
            this.movementComplete = false;
            calculatePositions();
            this.resetScript = false;
        }
    }

    #endregion
}